package com.atguigu.gulimallcart.interceptor;

import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimallcart.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @ClassName CartInterceptor
 * @Description TODO
 * @Detail    拦截器配置步骤：
 *                  1、编写一个类，实现HandlerInterceptor接口
 *                  2、重写拦截器方法
 *                  3、编写一个配置类，实现WebMvcConfigurer，配置拦截器拦截路径等信息
 * @Author MyPC
 * @Date 2020/7/13
 * @Version 1.0
 */
public class CartInterceptor implements HandlerInterceptor{
    //本地线程对象，同一线程的数据是共享的
    public static final ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();

    /**
     * controller方法执行之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserInfoTo userInfoTo=new UserInfoTo();
        HttpSession session = request.getSession();
        MemberVo memberVo = (MemberVo) session.getAttribute(AuthServiceConstant.SESSION_USER_NAME);
        if(memberVo !=null){
            //已经登陆过,设置用户id
            userInfoTo.setUserId(memberVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies !=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    //如果用户有携带了user-key，那么就设置好值
                    userInfoTo.setUserKey(cookie.getValue());
                    //设置标志位
                    userInfoTo.setTempUser(true);
                }
            }
        }
        //如果没有临时用户，一定封装一个临时用户
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String string = UUID.randomUUID().toString();
            userInfoTo.setUserKey(string);
        }
        //目标方法执行之前,将userInfoTo保存到threadLocal，同一线程中threadLocal的数据是共享的
        threadLocal.set(userInfoTo);
        //拦截器全部放行
        return true;
    }

    /**
     * Controller方法执行之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getTempUser()){
            //如果cookie已经设置过了，则无需再次设置了
            Cookie cookie=new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            //设置一个月过期
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
